// pages/Tabbar/Home/Home.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;
import { queryAppInforMation } from '../../../api/brand';
import { queryPetStore , queryPetInfo } from '../../../api/pet';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    assetsAddress: assetsAddress,
    CustomBar: app.globalData.CustomBar,
    statusBarHeight: wx.getSystemInfoSync().statusBarHeight,
    bannerList: [],
    shoppingName: '江城路店',
    queryLongitude: '',
    queryLatitude: '',
    tabbarHeight: wx.getSystemInfoSync().screenHeight - wx.getSystemInfoSync().safeArea.bottom + 60,
    petList: [],
    petInfo: {},
    petId: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var _this = this;
    if (wx.onNeedPrivacyAuthorization) {
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
      })
    }
    _this.getBannerList();
    // this._queryPetStore();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      console.log(this.getTabBar().data,'this.getTabBar()')
      this.getTabBar().setData({
        active: 0
      })
    }
    this._getLocation();
    this._queryPetInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getBannerList();
    this._queryPetInfo();
    setTimeout(() => {
      wx.stopPullDownRefresh({
        success: (res) => {
          console.log(res, '刷新成功')
          wx.showToast({
            title: '刷新成功',
            icon: 'none',
          })
        },
      })
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    let userId = wx.getStorageSync('userId') ?? 10;
    return {
      path: '/pages/Welcome/Welcome?scene='+userId,
    }
  },
  // 获取轮播图信息
  getBannerList() {
    let _this = this
    queryAppInforMation({ infoType: 1 })
    .then(res => {
      if (res.success) {
        _this.setData({
          bannerList: res.data.content
        })
      } else {
        wx.showToast({
          title: res.errMessage,
          icon: 'none'
        })
      }
    })
  },
  // 获取宠物门店
  _queryPetStore(){
    let _this = this;
    const { queryLongitude , queryLatitude } = _this.data;
    queryPetStore({page: 0,size: 1,queryLongitude: queryLongitude,queryLatitude: queryLatitude})
    .then(res => {
      if(res.success){
        _this.setData({
          shoppingName: res.data.content.length > 0 ? res.data.content[0].name : '',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  toLink(e){
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    console.log(item)
    if(item.jumpUrl != '' && item.jumpUrl != null && item.jumpUrl.substring(0,4) == 'http'){
      if(checkFile(item.jumpUrl) == 'image'){
        wx.navigateTo({
          url: `/pages/Link/LinkImg/LinkImg?url=${encodeURIComponent(item.jumpUrl)}&title=${JSON.stringify(item.title)}`,
        })
      }else{
        wx.navigateTo({
          url: `/pages/Link/Link/Link?url=${encodeURIComponent(item.jumpUrl)}&title=${JSON.stringify(item.title)}`,
        })
      }
    }
  },
  // 页面跳转
  goNext(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    let url = e.target.dataset.name||e.currentTarget.dataset.name;
    let item = e.target.dataset.item||e.currentTarget.dataset.item;
    wx.setStorageSync('selNearByStore','0');
    // console.log(JSON.stringify(item))
    // return
    if(item){
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}?item=${JSON.stringify(item)}`,
        })
      }
    }else{
      if(type == 1){
        wx.switchTab({
          url: `${url}`,
        })
      }else{
        wx.navigateTo({
          url: `${url}`,
        })
      }
    }
  },
  // 选择地图定位
  _getLocation(){
    console.log('定位')
    let _this = this;
    wx.getFuzzyLocation({
      type: 'gcj02',
      success: (res) => {
        console.log(res,'位置信息')
        const latitude = res.latitude
        const longitude = res.longitude
        wx.setStorageSync('longitude', longitude)
        wx.setStorageSync('latitude', latitude)
        _this.setData({
          queryLongitude: longitude,
          queryLatitude: latitude,
        })
        _this._queryPetStore();
      },
      fail: (err) => {
        console.log(err,'err')
      }  
    })
  },
  // 定位
  getUserAddress(e){
    var _this = this;
    wx.getSetting({
      success: (res) => {
        console.log(res,'res')
        if(res.authSetting['scope.getFuzzyLocation']){
          _this._getLocation();
        }else{
          wx.authorize({
            scope: 'scope.getFuzzyLocation',
            success: ()=>{
              _this._getLocation();
            },
            fail: (err) => {
              console.log(err,'err')
              wx.showModal({
                title: '获取定位信息',
                content: '请允许获取您的位置信息，否则小程序部分功能将无法使用',
                success: (res) => {
                  if(res.confirm){
                    wx.openSetting({
                      success: (res) => {
                        if(res.authSetting['scope.getFuzzyLocation']){
                          _this._getLocation();
                        }
                      },
                    })
                  }
                },
                fail: (e) => {
                  _this._queryPetStore();
                }
              })
            }
          })
        }
      }
    })
  },
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
    this._getLocation();
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
  },
  // 查询宠物信息
  _queryPetInfo(){
    let _this = this;
    queryPetInfo({id: _this.data.petId,userId: wx.getStorageSync('userId')})
    .then(res => {
      if(res.success){
        _this.setData({
          petList: res.data.content,
          petInfo: res.data.content.length > 0 ? res.data.content[0] : {}
        })
        console.log(_this.data.petList,'petList')
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 选择宠物
  selPet(){
    let _this = this;
    wx.navigateTo({
      url: '/pages/Pet/PetList/PetList',
      events: {
        selPetInfo: function(data){
          console.log(data.data);
          _this.setData({
            petId: data.data,
          })
          _this._queryPetInfo();
        }
      }
    })
  },
})